#include "device.h"
#include <QDebug>
#include <QMessageBox>

Device::Device(QObject *parent) :
    QObject(parent)
{
    m_receiver.m_port=&m_port;
    connect(&m_receiver,SIGNAL(finished()),this,SLOT(onDataReady()));
}

bool Device::open(const QString& port)
{
    if(m_port.isOpen())
        m_port.close();

    m_port.setPortName(port);
    m_port.setBaudRate(BAUD9600);
    m_port.setFlowControl(FLOW_OFF);
    m_port.setParity(PAR_NONE);
    m_port.setDataBits(DATA_8);
    m_port.setStopBits(STOP_1);


    return m_port.open(QIODevice::ReadWrite);
}

bool Device::IsOpen()
{
    return m_port.isOpen();
}

void Device::Obtain()
{
    if(!m_receiver.isRunning())
        m_receiver.start();
    else
        QMessageBox::critical((QWidget*)parent(),"Obtain Data","The port is busy");

}

void Device::onDataReady()
{
    m_measureList=m_receiver.m_measures;
    m_receiver.m_measures.clear();

    emit DataReady();
}

const MeasureList& Device::measureList()
{
    return m_measureList;
}

void Device::SetConfig(QDateTime date,uint8_t refresh)
{
    QByteArray array;
    // Start
    array.append(40);
    // Year
    array.append(char(date.date().year()-2000));
    // Month
    array.append(char(date.date().month()));
    // Day
    array.append(char(date.date().day()));

    // Hour
    array.append(char(date.time().hour()));
    // Minute
    array.append(char(date.time().minute()));
    // Second
    array.append(char(date.time().second()));

    // Refresh time
    array.append(char(refresh));

    // Send it
    m_port.write(array);
}
